<template>
  <div class="dashboard-container">
    <!-- 统计卡片 -->
    <div class="stat-cards">
      <el-row :gutter="24">
        <!-- 岗位申请统计 -->
        <el-col :span="12">
          <el-card class="stat-card" shadow="hover">
            <div class="stat-header">
              <div class="stat-icon">
                <el-icon><Briefcase /></el-icon>
              </div>
              <div class="stat-title">岗位申请</div>
            </div>
            <div class="stat-content">
              <div class="stat-item">
                <div class="label">总申请数</div>
                <div class="value">{{ stats.totalJobApplications }}</div>
              </div>
              <div class="stat-item">
                <div class="label">待审核</div>
                <div class="value">{{ stats.pendingJobApplications }}</div>
              </div>
              <div class="stat-item">
                <div class="label">已通过</div>
                <div class="value">{{ stats.approvedJobApplications }}</div>
              </div>
            </div>
          </el-card>
        </el-col>

        <!-- 奖学金申请统计 -->
        <el-col :span="12">
          <el-card class="stat-card" shadow="hover">
            <div class="stat-header">
              <div class="stat-icon">
                <el-icon><Money /></el-icon>
              </div>
              <div class="stat-title">奖学金申请</div>
            </div>
            <div class="stat-content">
              <div class="stat-item">
                <div class="label">总申请数</div>
                <div class="value">{{ stats.totalScholarshipApplications }}</div>
              </div>
              <div class="stat-item">
                <div class="label">待审核</div>
                <div class="value">{{ stats.pendingScholarshipApplications }}</div>
              </div>
              <div class="stat-item">
                <div class="label">已通过</div>
                <div class="value">{{ stats.approvedScholarshipApplications }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 公告和图表区域 -->
    <div class="charts-and-notices">
      <el-row :gutter="24">
        <!-- 申请趋势图 -->
        <el-col :span="14">
          <el-card class="chart-card" shadow="hover">
            <div class="chart-header">
              <div class="chart-title">申请趋势</div>
            </div>
            <div class="chart-content">
              <div ref="applicationChartRef" style="height: 300px"></div>
            </div>
          </el-card>
        </el-col>

        <!-- 公告列表 -->
        <el-col :span="10">
          <el-card class="notice-card" shadow="hover">
            <template #header>
              <div class="notice-header">
                <span>最新公告</span>
              </div>
            </template>
            <div class="notice-list">
              <el-scrollbar height="250px">
                <div v-for="notice in notices" :key="notice.id" class="notice-item">
                  <div class="notice-title" @click="viewNoticeDetail(notice)">
                    {{ notice.title }}
                  </div>
                  <div class="notice-meta">
                    <span class="notice-time">{{ formatDate(notice.createTime) }}</span>
                    <span v-if="notice.important" class="notice-tag">重要</span>
                  </div>
                </div>
                <el-empty v-if="!notices?.length" description="暂无公告" />
              </el-scrollbar>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
export default {
  name: 'StudentDashboard'
}
</script>

<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Briefcase, Money } from '@element-plus/icons-vue'
import { getDashboardStats } from '@/api/student/dashboard'
import * as echarts from 'echarts'
import { getNotices } from '@/api/student/notice'
import { formatDate } from '@/utils/date'

// 初始化数据结构
const stats = ref({
  totalJobApplications: 0,
  pendingJobApplications: 0,
  approvedJobApplications: 0,
  totalScholarshipApplications: 0,
  pendingScholarshipApplications: 0,
  approvedScholarshipApplications: 0,
  months: [],
  jobTrends: [],
  scholarshipTrends: []
})

const applicationChartRef = ref(null)
let applicationChart = null
const loading = ref(false)

// 公告相关
const notices = ref([])

// 获取统计数据
const fetchStats = async () => {
  try {
    loading.value = true
    const response = await getDashboardStats()
    console.log('Response data:', response)
    Object.assign(stats.value, response)
    console.log('Updated stats:', stats.value)
  } catch (error) {
    console.error('Failed to fetch stats:', error)
    ElMessage.error(error.response || '获取统计数据失败')
  } finally {
    loading.value = false
  }
}

// 获取公告列表
const fetchNotices = async () => {
  try {
    const { content } = await getNotices({ 
      page: 0,
      size: 5,
      search: '' 
    })
    console.log('Notices response:', content)  // 添加日志
    notices.value = content || []
    console.log('Updated notices:', notices.value)  // 添加日志
  } catch (error) {
    console.error('Failed to fetch notices:', error)
    ElMessage.error('获取公告失败')
    notices.value = []
  }
}

// 初始化申请趋势图
const initApplicationChart = () => {
  if (!applicationChartRef.value) {
    console.warn('Application chart ref not found')
    return
  }
  
  try {
    if (applicationChart) {
      applicationChart.dispose()
    }
    
    applicationChart = echarts.init(applicationChartRef.value)
    const option = {
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: ['岗位申请', '奖学金申请']
      },
      xAxis: {
        type: 'category',
        data: stats.value.months || []
      },
      yAxis: {
        type: 'value',
        name: '申请数量'
      },
      series: [
        {
          name: '岗位申请',
          type: 'line',
          smooth: true,
          data: stats.value.jobTrends || []
        },
        {
          name: '奖学金申请',
          type: 'line',
          smooth: true,
          data: stats.value.scholarshipTrends || []
        }
      ]
    }
    applicationChart.setOption(option)
  } catch (error) {
    console.error('Failed to init application chart:', error)
  }
}

// 监听窗口大小变化
const handleResize = () => {
  applicationChart?.resize()
}

// 查看公告详情
const viewNoticeDetail = (notice) => {
  ElMessageBox.alert(notice.content, notice.title, {
    confirmButtonText: '确定'
  })
}

// 组件挂载时初始化
onMounted(async () => {
  console.log('Component mounted')
  await fetchStats()
  console.log('Stats fetched:', stats.value)
  initApplicationChart()
  await fetchNotices()
  window.addEventListener('resize', handleResize)
})

// 组件卸载时清理
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  applicationChart?.dispose()
})

// 监听数据变化
watch(stats, (newVal) => {
  console.log('Stats changed:', newVal)
  initApplicationChart()
}, { deep: true })
</script>

<style scoped>
.dashboard-container {
  padding: 24px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);
}

.stat-cards {
  margin-bottom: 24px;
}

.stat-card {
  height: 100%;
  background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
  border: none;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.05);
  transition: all 0.3s ease;
  
  .stat-header {
    display: flex;
    align-items: center;
    margin-bottom: 24px;
    padding: 16px;
    border-bottom: 1px solid rgba(0,0,0,0.05);
    
    .stat-icon {
      font-size: 28px;
      margin-right: 12px;
      color: #409EFF;
      background: rgba(64,158,255,0.1);
      padding: 12px;
      border-radius: 10px;
    }
    
    .stat-title {
      font-size: 18px;
      font-weight: 600;
      color: #2c3e50;
    }
  }
  
  .stat-content {
    padding: 0 16px 16px;
  
    .stat-item {
      margin-bottom: 16px;
      padding: 12px;
      background: rgba(255,255,255,0.6);
      border-radius: 8px;
      transition: all 0.3s ease;
      
      &:hover {
        background: rgba(255,255,255,0.9);
        transform: translateY(-2px);
      }
      
      .label {
        font-size: 14px;
        color: #606266;
        margin-bottom: 8px;
      }
      
      .value {
        font-size: 24px;
        font-weight: 600;
        color: #2c3e50;
        line-height: 1;
      }
    }
  }

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 24px rgba(0,0,0,0.1);
  }
}

.charts-and-notices {
  margin-top: 24px;
}

.chart-card {
  background: #ffffff;
  border: none;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.05);
  
  .chart-header {
    padding: 16px;
    border-bottom: 1px solid rgba(0,0,0,0.05);
    
    .chart-title {
      font-size: 18px;
      font-weight: 600;
      color: #2c3e50;
    }
  }
  
  .chart-content {
    padding: 16px;
    height: 350px;
  }
}

.notice-card {
  background: #ffffff;
  border: none;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.05);
  
  .notice-header {
    padding: 16px;
    border-bottom: 1px solid rgba(0,0,0,0.05);
    
    span {
      font-size: 18px;
      font-weight: 600;
      color: #2c3e50;
    }
  }
  
  .notice-list {
    padding: 0 16px;
  
    .notice-item {
      padding: 16px;
      border-bottom: 1px solid rgba(0,0,0,0.05);
      transition: all 0.3s ease;
      cursor: pointer;
      
      &:hover {
        background: rgba(64,158,255,0.05);
        border-radius: 8px;
      }
      
      .notice-title {
        font-size: 15px;
        color: #2c3e50;
        margin-bottom: 8px;
        font-weight: 500;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      
      .notice-meta {
        display: flex;
        align-items: center;
        
        .notice-time {
          color: #909399;
        }
        
        .notice-tag {
          background: #f56c6c;
          color: white;
          padding: 2px 8px;
          border-radius: 4px;
          font-size: 12px;
          margin-left: 8px;
        }
      }
    }
  }
}

/* 卡片hover效果 */
.el-card {
  transition: all 0.3s;
  
  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
  }
}

.notice-tag {
  background-color: #f56c6c;
  color: white;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
  margin-left: 8px;
}

.notice-title {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style> 